package org.jtrace.geometry;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.jtrace.Hit;
import org.jtrace.Jay;
import org.jtrace.Material;
import org.jtrace.Materials;
import org.jtrace.NotHit;
import org.jtrace.examples.io.SimplePLYExample;
import org.jtrace.io.PlyReader;
import org.jtrace.primitives.ColorRGB;
import org.jtrace.primitives.Point3D;

public class BoundedMesh extends Mesh {
	private Set<BoundingBox> boxes = new LinkedHashSet<BoundingBox>();	
	
	public BoundedMesh(String plyPath, Material material) {
		super(material);
		
		center = new Point3D(0, 0, 0);
		min = new Point3D(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);
		max = new Point3D(Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE);
		
		loadMesh(plyPath);
	}
	
	private void loadMesh(String plyPath) {
		InputStream is = SimplePLYExample.class.getResourceAsStream(plyPath);
		
		try {
			List<Triangle> triangles = PlyReader.read(is, Materials.metallic(ColorRGB.RED));
			
			BoundingBox box = new BoundingBox();
			
			for(Triangle triangle : triangles) {
				box.addTriangle(triangle);
				
				updateBounds(triangle.getV1());
				updateBounds(triangle.getV2());
				updateBounds(triangle.getV3());
				
				if (box.getTrianglesCount() >= (triangles.size()/4.0)) {
					boxes.add(box);
					box = new BoundingBox();
				}
			}
			
			if (box.getTrianglesCount() > 0) {
				boxes.add(box);
			}
			
			updateCenter();
			
			//this.triangles.addAll(triangles);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Hit hit(Jay jay) {
		Hit hit = new NotHit();
		
		for (BoundingBox box : boxes) {
			Hit newHit = box.hit(jay);
			
			if ((newHit.isHit() && !hit.isHit()) || (newHit.isHit() && hit.isHit() && newHit.getT() < hit.getT()))
				hit = newHit;
		}
		
		return hit;
	}
}
